/*
 * @(#)PagerTag.java 
 * 
 * Project: CUPSecureBM
 * 
 * Modify Information:
 * =============================================================================
 * Author           Date              Description 
 * hitrust          2005-12-7         first release
 * 
 * Copyright Notice:
 * =============================================================================
 * Copyright (c) 2001-2005 Beijing HiTRUST Technology Co., Ltd. 1808 Room,
 * Science & Technology Building, No. 9 South Street, Zhong Guan Cun, Haidian
 * District, Beijing ,100081, China All rights reserved.
 * 
 * This software is the confidential and proprietary information of Beijing
 * HiTRUST Technology Co., Ltd. ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in accordance
 * with the terms of the license agreement you entered into with HiTRUST.
 * 
 * Warning:
 * =============================================================================
 * 
 */
package com.hitrust.gs.util.page.taglib.page;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.hitrust.gs.util.page.ParamUtil;


/**
 * 分页框架标记
 * 将分页控制的参数予以保存并自动生成包含对应的<input type=hidden>的div
 * 通过计算当前的页号,操作,以及控制每页记录数,提供起始记录号,和每页显示记录数,
 * 供框架内的程序控制显示起始的记录位置和数量
 * 使用举例:
 * <pre>
 *  <code>
 *    int tTotalRecord = getCount();//获得记录总数
 *    condition=request.getParameter("condition");
 *    <page:pager total=<%=tTotalRecord%> defaultPageSize='20'>
 *      <%
 *        //TODO：body方法
 *      %>
 *    </page:pager>
 *  </code>
 * <pre>
 */
public class PagerTag extends BodyTagSupport {
    private static final long serialVersionUID = -6252620157460385197L;
    private StringBuffer output;        //保存输出
    private int pageNo;                 //当前页面
    private int pageSize;               //每页记录数
    private int index = 1;              //起始记录数,缺省为0
    private int pages;                  //总页数
    private boolean resume = false;     //是否是恢复操作
    private int total = 0;              //记录总数,即需要分页显示的记录总数,初始化默认为0
    private int defaultPageSize = 10;   //缺省每页记录数,可在导航条中改变每页记录数的值

    public void setTotal(int newTotal) {
        total = newTotal;
    }

    public void setDefaultPageSize(int newDefaultPageSize) {
        defaultPageSize = newDefaultPageSize;
    }
    /**
     * 调用handler进行分页处理
     */
    public int doStartTag() throws JspTagException {
        output = new StringBuffer();
        resume = false;
        String bar =handler();
        try {
            pageContext.getOut().write(bar);
        }
        catch (IOException e) {
            
            e.printStackTrace();
        }
        return EVAL_BODY_INCLUDE;
    }

    /**
     * 获得标记内的记录列表内容
     */
    public int doAfterBody() throws JspTagException {
        BodyContent bodyContent = getBodyContent();
        if (bodyContent != null) {
            output.append(bodyContent.getString());
            try {
                bodyContent.clear();
            }
            catch (IOException ex) {
                throw new JspTagException("Fatal IO Error");
            }
        }
        return SKIP_BODY;
    }

    /**
     * 输出标记内的内容
     */
    public int doEndTag() throws JspTagException {
        BodyContent bodyContent = getBodyContent();
        try {
            if (bodyContent != null) {
                //输出结束标记
                output.append("</div>\n");
                //输出全部内容
                bodyContent.getEnclosingWriter().write(output.toString());
            }
        }
        catch (IOException ex) {
            throw new JspTagException("Fatal IO Error");
        }

        return EVAL_PAGE;
    }

    /**
     * 设置标记内变量(每页记录数,当前页号,起始记录号,表单的查询字符串)
     */
    public void setVariable() {
        pageContext.setAttribute("pageSize", new Integer(pageSize));
        pageContext.setAttribute("pageNo", new Integer(pageNo));
        pageContext.setAttribute("total", new Integer(total));
        pageContext.setAttribute("pages", new Integer(pages));
        pageContext.setAttribute("index", new Integer(index));
    }

    /**
     * 获取分页信息和其它表单中的变量值并输出表单
     */
    private String handler() {
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        StringBuffer paramBuf = new StringBuffer();
        String choice = "";


        //获取操作
        choice = ParamUtil.getParameter(request, "choice");
               

        //获取每页记录数,若没指定,使用默认值
        pageSize = ParamUtil.getIntParameter(request, "pageSize", defaultPageSize);
        
        //*******************ZT改
        String m_myPageSize = pageContext.getRequest().getParameter("m_mypagesize");
        if(m_myPageSize!=null&&!m_myPageSize.equals("")){
        	pageSize = Integer.parseInt(m_myPageSize);
        }
        //*******************ZT改
        
        //获取页号
        pageNo = ParamUtil.getIntParameter(request, "pageNo", 1);

        //每页记录数越界处理
        if (pageSize <= 0)
            pageSize = 1;

        //计算总页数
        pages = (total % pageSize == 0) ? total / pageSize : total / pageSize + 1;
        
        //根据操作,重新确定当前页号
        if (choice.equals("next"))
            pageNo++;
        if (choice.equals("prev"))
            pageNo--;
        if (choice.equals("first"))
            pageNo = 1;
        if (choice.equals("last"))
            pageNo = pages;
        
        if(choice.equals(""))
            pageNo = 1;

        //页号越界处理
        if (pageNo > pages)
            pageNo = pages;
        if (pageNo <= 0)
            pageNo = 1;

        //起始记录号
        index = (pageNo - 1) * pageSize + 1;
        output.append("<div>\n");

        //输出分页参数表单
        paramBuf.append("<input type='hidden' name='pageNo' value='" + pageNo + "'>\n");
        paramBuf.append("<input type='hidden' name='pageSize' value='" + pageSize + "'>\n");
        paramBuf.append("<input type='hidden' name='choice' value=''>\n");
        paramBuf.append("<input type='hidden' name='totalRecords' value='"+total+"'>\n");

        output.append(paramBuf.toString());
        setVariable();
        if (resume) {
            //转出恢复情况下需重新提交表单
            String resend = "<script language='javascript'>"
                            + "document.pager.submit();"
                            + "</script>\n";
            output.append(resend);
            System.out.println("output=" + output.toString());
        }
        return output.toString();
    }

}
